'use strict'

import React, { Component } from 'react'
import * as color from '../../configs/color'
import noop from 'lodash/noop'

const bedStyle = {
    position: 'relative',
    display: 'block',
    borderRadius: '16px',
    border: '1px solid #44DB5E',
    width: '52px',
    height: '32px',
    outline: '0',
    boxSizing: 'border-box',
    background: '#fff'
}

const buttonStyle = {
    position: 'absolute',
    left: '1px',
    top: '1px',
    width: '28px',
    height: '28px',
    background: '#fff',
    borderRadius: '15px',
    boxShadow: '0 1px 3px rgba(0,0,0,.4)'
}

export default class Switch extends Component {
    constructor(props) {
        super(props)
        this.state = {
            value: this.props.value
        }
        this.handleClick = this.handleClick.bind(this)
    }

    handleClick() {
        this.setState({
            value: !this.state.value
        }, () => {
            this.props.onChange(this.state.value)
        })
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.value != this.state.value) {
            this.setState({
                value: nextProps.value
            })
        }
    }

    render() {
        let renderBedStyle = Object.assign({}, bedStyle);
        let renderButtonStyle = Object.assign({}, buttonStyle);
        if (this.state.value) {
            renderBedStyle.background = color.SWITCH;
            renderButtonStyle.transform = 'translateX(20px)';
        } else {
            renderBedStyle.border = '1px solid #ddd';
        }
        return (
            <div onClick={this.handleClick} style={renderBedStyle}>
                <div style={renderButtonStyle}></div>
            </div>
        )
    }
}

Switch.defaultProps = {
    onChange: noop,
    color: color.SWITCH,
    value: false
}
